package ReentrantLock_3;
import java.util.concurrent.locks.ReentrantLock;
class ResourceAccess {
    private final ReentrantLock fairLock = new ReentrantLock(true); // 公平锁
    private final ReentrantLock unfairLock = new ReentrantLock();   // 非公平锁
    public void accessWithFairLock() {
        fairLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 获取公平锁");
            Thread.sleep(20); // 模拟资源访问时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            fairLock.unlock();
        }
    }

    public void accessWithUnfairLock() {
        unfairLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 获取非公平锁");
            Thread.sleep(20); // 模拟资源访问时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            unfairLock.unlock();
        }
    }
}

public class 公平锁vs非公平锁_资源访问 {
    public static void main(String[] args) {
        final ResourceAccess resource = new ResourceAccess();

        // 创建30个访问公平锁的线程
        for (int i = 0; i < 30; i++) {
            new Thread(new Runnable() {
                public void run() {
                    resource.accessWithFairLock();
                }
            }, "公平锁线程-" + i).start();
        }

        // 创建30个访问非公平锁的线程
        for (int i = 0; i < 30; i++) {
            new Thread(new Runnable() {
                public void run() {
                    resource.accessWithUnfairLock();
                }
            }, "非公平锁线程-" + i).start();
        }
    }
}